package pl.lodz.p.kipme.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;

import pl.lodz.p.kipme.bo.Product;
import pl.lodz.p.kipme.bo.Transaction;
import pl.lodz.p.kipme.entities.ProductEntity;
import pl.lodz.p.kipme.entities.TransactionEntity;
import pl.lodz.p.kipme.util.ProductUtil;
import pl.lodz.p.kipme.util.TransactionUtil;

public class TransactionDAOImpl extends BasicDaoSupport implements TransactionDAO{

	@Override
	public void addTransaction(Transaction transaction) {
    	session.beginTransaction();
        session.persist(new TransactionEntity(transaction));
        session.getTransaction().commit();
	}

	@Override
	public List<Transaction> getTransactionsBetweenDates(Date startDate, Date endDate) {
        Query createQuery = session.createQuery("from TransactionEntity where saleDate between :start and :end ");
        createQuery.setParameter("start", startDate);
        createQuery.setParameter("end", endDate);
        List<TransactionEntity> list = createQuery.list();
        List<Transaction> result = new ArrayList<Transaction>();
        for (TransactionEntity entity : list) {
            result.add(TransactionUtil.transactionEntity2Transaction(entity));
        }
        return result;
	}

	@Override
	public List<Transaction> getTransactionsByProductCode(String productCode) {
        Query createQuery = session.createQuery("from TransactionEntity where productCode = :productCode");
        createQuery.setParameter("productCode", productCode);
        List<TransactionEntity> list = createQuery.list();
        List<Transaction> result = new ArrayList<Transaction>();
        for (TransactionEntity entity : list) {
            result.add(TransactionUtil.transactionEntity2Transaction(entity));
        }
        return result;
	}

	@Override
	public List<Transaction> getAllTransaction() {
        Query createQuery = session.createQuery("from TransactionEntity");
        List<TransactionEntity> list = createQuery.list();
        List<Transaction> result = new ArrayList<Transaction>();
        for (TransactionEntity entity : list) {
            result.add(TransactionUtil.transactionEntity2Transaction(entity));
        }
        return result;
	}

}
